# -*- coding: UTF-8 -*-

import socket
import base64
import sys
import time
import datetime
import json
import hmac
from hashlib import sha1 as sha

import oss2 as oss2

from .config import *


class AliOss(object):
    # 请填写您的AccessKeyId。

    def __init__(self, key):
        self.access_key_id = 'LTAIiosZDykryZAO'
        self.access_key_secret = 'nW122V2ywcskMkEfgAvHOM4riVBIjG'
        self.host = 'http://oss-cn-beijing.aliyuncs.com'
        self.upload_dir = 'report/'
        self.key = key

    @staticmethod
    def get_iso_8601(expire):
        gmt = datetime.datetime.utcfromtimestamp(expire).isoformat()
        gmt += 'Z'
        return gmt

    def get_token(self):
        now = int(time.time())
        expire_syncpoint = now + expire_time
        expire_syncpoint = 1612345678
        expire = self.get_iso_8601(expire_syncpoint)

        policy_dict = {}
        policy_dict['expiration'] = expire
        condition_array = []
        array_item = []
        array_item.append('starts-with')
        array_item.append('$key')
        array_item.append(self.upload_dir)
        condition_array.append(array_item)
        policy_dict['conditions'] = condition_array
        policy = json.dumps(policy_dict).strip()
        policy_encode = base64.b64encode(policy.encode())
        h = hmac.new(self.access_key_secret.encode(), policy_encode, sha)
        sign_result = base64.encodestring(h.digest()).strip()
        token_dict = {}
        token_dict['accessid'] = self.access_key_id
        token_dict['host'] = self.host
        token_dict['policy'] = policy_encode.decode()
        token_dict['signature'] = sign_result.decode()
        token_dict['expire'] = expire_syncpoint
        token_dict['dir'] = self.upload_dir
        result = json.dumps(token_dict)
        return result

    def upload(self, file):

        # 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        # Endpoint以杭州为例，其它Region请按实际情况填写。
        bucket = oss2.Bucket(auth, self.host, 'samereport')

        # 必须以二进制的方式打开文件，因为需要知道文件包含的字节数。
        with open(file, 'rb') as fileobj:
            # Seek方法用于指定从第1000个字节位置开始读写。上传时会从您指定的第1000个字节位置开始上传，直到文件结束。
            bucket.put_object(self.upload_dir+'samereport_'+self.key+'.zip', fileobj)
# def do_POST(server):
#     """
#     启用 POST 调用处理逻辑
#     :param server: Web HTTP Server 服务
#     :return:
#     """
#     print("********************* do_POST ")
#     # get public key
#     pub_key_url = ''
#
#     try:
#         pub_key_url_base64 = server.headers['x-oss-pub-key-url']
#         pub_key = httpserver.get_pub_key(pub_key_url_base64)
#     except Exception as e:
#         print(str(e))
#         print('Get pub key failed! pub_key_url : ' + pub_key_url)
#         server.send_response(400)
#         server.end_headers()
#         return
#
#     # get authorization
#     authorization_base64 = server.headers['authorization']
#
#     # get callback body
#     content_length = server.headers['content-length']
#     callback_body = server.rfile.read(int(content_length))
#
#     # compose authorization string
#     auth_str = ''
#     pos = server.path.find('?')
#     if -1 == pos:
#         auth_str = server.path + '\n' + callback_body.decode()
#     else:
#         auth_str = httpserver.get_http_request_unquote(server.path[0:pos]) + server.path[pos:] + '\n' + callback_body
#
#     result = httpserver.verrify(auth_str, authorization_base64, pub_key)
#
#     if not result:
#         print('Authorization verify failed!')
#         print('Public key : %s' % (pub_key))
#         print('Auth string : %s' % (auth_str))
#         server.send_response(400)
#         server.end_headers()
#         return
#
#     # response to OSS
#     resp_body = '{"Status":"OK"}'
#     server.send_response(200)
#     server.send_header('Content-Type', 'application/json')
#     server.send_header('Content-Length', str(len(resp_body)))
#     server.end_headers()
#     server.wfile.write(resp_body.encode())


# def do_GET(server):
#     """
#     启用 Get 调用处理逻辑
#     :param server: Web HTTP Server 服务
#     :return:
#     """
#     print("********************* do_GET ")
#     token = get_token()
#     server.send_response(200)
#     server.send_header('Access-Control-Allow-Methods', 'POST')
#     server.send_header('Access-Control-Allow-Origin', '*')
#     server.send_header('Content-Type', 'text/html; charset=UTF-8')
#     server.end_headers()
#     server.wfile.write(token.encode())


# if '__main__' == __name__:
#     # 在服务器中, 0.0.0.0指的是本机上的所有IPV4地址, 如果一个主机有两个IP地址,
#     # 192.168.1.1 和 10.1.2.1, 并且该主机上的一个服务监听的地址是0.0.0.0, 那么通过两个IP地址都能够访问该服务。
#     # server_ip = get_local_ip() 若用户希望监听本机外网IPV4地址，则采用本行代码并注释掉下一行代码
#     server_ip = "0.0.0.0"
#     server_port = 8080
#     if len(sys.argv) == 2:
#         server_port = int(sys.argv[1])
#     if len(sys.argv) == 3:
#         server_ip = sys.argv[1]
#         server_port = int(sys.argv[2])
#     print("App server is running on http://%s:%s " % (server_ip, server_port))
#
#     server = httpserver.MyHTTPServer(server_ip, server_port)
#     server.serve_forever()
